import { BusinessError } from '@kit.BasicServicesKit'
import { common, Want } from '@kit.AbilityKit'
import { call } from '@kit.TelephonyKit'
import { productViewManager } from '@kit.StoreKit'
import { logUtils } from './LogUtils'

export class SystemApi {
  private static readonly TAG = 'SystemApi'

  static call(phoneNumber: string) {
    if (canIUse('SystemCapability.Applications.Contacts')) {
      call.makeCall(phoneNumber).then(() => {
        logUtils.log(SystemApi.TAG, "call success")
      }).catch((err: BusinessError) => {
        logUtils.log(SystemApi.TAG, `call error:(${err.code})${err.message}`)
      })
    } else {
      logUtils.log(SystemApi.TAG, 'call error: not support')
    }
  }

  static goAppMarket(context: common.UIAbilityContext, bundleName: string) {
    try {
      productViewManager.loadProduct(context, {
        bundleName: bundleName
      }, {
        onError: (error: BusinessError) => {
          logUtils.log(SystemApi.TAG, `error:(${error.code})${error.message}`)
        }
      })
    } catch (err) {
      logUtils.log(SystemApi.TAG, `goAppMarket error:(${err.code})${err.message}`)
    }
  }

  /**
   * 打开系统应用设置页面
   */
  static openSetting(context: common.UIAbilityContext) {
    let wantInfo: Want = {
      bundleName: 'com.huawei.hmos.settings',
      abilityName: 'com.huawei.hmos.settings.MainAbility',
      uri: 'application_info_entry',
      parameters: {
        pushParams: context.applicationInfo.name // 打开指定应用的详情页面
      }
    }
    try {
      context.startAbility(wantInfo).then(() => {
        logUtils.log(SystemApi.TAG, "openSetting success")
      }).catch((err: BusinessError) => {
        logUtils.log(SystemApi.TAG, `openSetting error:(${err.code})${err.message}`)
      })
    } catch (err) {
      logUtils.log(SystemApi.TAG, `openSetting error:(${err.code})${err.message}`)
    }
  }
}